import csv
import os
import re
import subprocess
import time
import warnings
from datetime import datetime, timedelta

import clipboard
import pandas as pd
import pyautogui
from mon.baselib.utils import StringUtils
from openpyxl import Workbook

from src.model.DayLink import DayLink
from src.model.ParseTask import ParseTask

warnings.filterwarnings('ignore')


def parse_task_by_file_name(file_path_prefix, file_name, user_name, station):
    file_path = os.path.join(file_path_prefix, file_name)
    return parse_task_by_file_path(file_path, user_name, station)


def parse_task_by_file_path(file_path, user_name, station):
    task_time = get_date_from_filename(file_path)
    task_model = ParseTask()
    task_model.name = user_name
    task_model.time = task_time
    with open(file_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        for row in reader:
            if len(row) <= 5:
                continue
            if row[3] == user_name:
                task_model.task = row[5].strip()
                task_model.station = station
                return task_model
    return task_model


def get_date_from_filename(file_path):
    """
    从文件名中提取日期
    参数:
        file_path (str): 文件的完整路径
    返回:
        str: 提取的日期，格式为 'YYYY年MM月DD日'，如果未找到则返回提示信息
    """
    # 从路径中提取文件名
    file_name = os.path.basename(file_path)
    file_name = file_name.replace(" ", "")
    # 使用正则表达式提取月份和日期
    match = re.search(r'(\d+)月(\d+)日', file_name)
    if match:
        month = int(match.group(1))  # 提取月份
        day = int(match.group(2))  # 提取日期
        # 默认使用当前年份
        year_num = int(year)
        # 构造日期
        date = datetime(year_num, month, day)
        return date.strftime("%Y%m%d")
    else:
        return "未找到日期信息"


chrome_path = 'C:/Users/Administrator/AppData/Local/Google/Chrome/Application/chrome.exe'


def download_csv(url, times):
    subprocess.Popen([chrome_path, url], shell=True)
    time.sleep(6)
    pyautogui.click(1739, 144)
    pyautogui.moveTo(1558, 260, duration=0.5)
    pyautogui.moveTo(1342, 301, duration=0.5)
    pyautogui.click(1342, 301)
    if times > 1:
        pyautogui.click(253, 15, duration=1)


def list_to_numbered_string(items):
    if len(items) == 0:
        return ''
    numbered_items = []
    for index, item in enumerate(items, start=1):
        numbered_items.append(f"{index}.{item}")
    return '\n'.join(numbered_items)


def config_task(task):
    new_task = []
    lines = task.split('\n')
    for index, line in enumerate(lines):
        if len(line) < 5:
            continue
        new_text = re.sub(r'^\d+[.、]', '', line).strip()
        if user_name == '董荣军':
            if '需求' in line:
                continue
            if '本周' in line:
                continue
            if new_text.startswith('Bug') or new_text.startswith('bug'):
                continue
        new_task.append(new_text)
    return list_to_numbered_string(new_task)


def get_link(text):
    url_pattern = r'https:\/\/[^\s]+'
    urls = re.findall(url_pattern, text)
    for url in urls:
        if StringUtils.not_empty(url):
            return url
    print('>>>>>>>>>' + text)
    return ''


def get_task_by_link():
    start_date = datetime.strptime('20250103', '%Y%m%d')
    days = []
    for i in range(60):
        current_date = start_date + timedelta(days=i)
        month = current_date.month
        weekday = current_date.weekday()
        if weekday == 6:
            continue
        day = current_date.day
        day_link = DayLink()
        day_link.day_num = current_date.strftime("%Y%m%d")
        day_link.time_str = f"{month}月{day}日"
        days.append(day_link)
    return days


def get_all_links(times, item, ws, wb, excel_file_path):
    if times % 5 == 0:
        print(f"正在暂停5s")
        time.sleep(5)
    print(f"正在获取链接[{times},{item.day_num}]")
    pyautogui.moveTo(863, 247)
    time.sleep(0.5)
    pyautogui.click()
    pyautogui.hotkey('ctrl', 'a')
    time.sleep(0.5)
    pyautogui.press('delete')
    time.sleep(0.5)
    clipboard.copy("tab=uba9qp " + item.time_str)
    pyautogui.hotkey('ctrl', 'v')
    # 移动到链接
    pyautogui.moveTo(938, 375, duration=0.5)
    pyautogui.rightClick(duration=0.5)
    # 移动到复制
    time.sleep(0.5)
    pyautogui.moveTo(975, 415)
    time.sleep(0.5)
    pyautogui.click(975, 415)
    content = clipboard.paste()
    link = get_link(content)
    item.link = link
    pyautogui.moveTo(938, 375)
    pyautogui.scroll(-350)
    # 写入 Excel 文件
    ws.append([item.day_num, item.link])
    wb.save(excel_file_path)


def get_urls_main():
    excel_file_path = r'C:\Users\Administrator\Downloads\all_urls.xlsx'

    # 创建一个新的 Excel 工作簿
    wb = Workbook()
    ws = wb.active

    # 写入表头
    ws.append(['日期', '链接'])

    all_day = get_task_by_link()
    for index, day_item in enumerate(all_day):
        get_all_links(index, day_item, ws, wb, excel_file_path)

    # 保存 Excel 文件
    wb.save(excel_file_path)


def download_all_file(begin_day_num):
    all_urls = []
    excel_file_path = r'C:\Users\Administrator\Downloads\all_urls.xlsx'
    df = pd.read_excel(excel_file_path)
    times = 1
    for index, row in df.iterrows():
        date = row['日期']
        if date < begin_day_num:
            continue
        link = row['链接']
        if isinstance(link, float):
            continue
        all_urls.append(link)
        print(f"正在下载[{times},{date}]")
        download_csv(link, times)
        times += 1
    return all_urls


def generator_task_excel():
    download_dir = r'C:\Users\Administrator\Downloads\task_csv_' + year
    csv_files = [f for f in os.listdir(download_dir) if f.endswith('.csv')]
    all_tasks = []
    for csv_file in csv_files:
        task_model = parse_task_by_file_name(download_dir, csv_file, user_name, station)
        if StringUtils.is_empty(task_model.task):
            continue
        if len(task_model.task) < 5:
            continue
        all_tasks.append(task_model)
    all_tasks.sort(key=lambda t: t.time)

    for task in all_tasks:
        new_task = config_task(task.task)
        task.task = new_task

    all_tasks_new = list(filter(lambda t: StringUtils.not_empty(t.task) and len(t.task) > 5 and t.task.strip() != '', all_tasks))

    data = {
        '日期': [task.time for task in all_tasks_new],
        '姓名': [task.name for task in all_tasks_new],
        '岗位': [task.station for task in all_tasks_new],
        '完成功能点/完成任务': [task.task for task in all_tasks_new],
    }
    df = pd.DataFrame(data)
    excel_file_path = f'C:\\Users\\Administrator\\Downloads\\all_tasks_{user_name}_{year}.xlsx'
    df.to_excel(excel_file_path, index=False)


if __name__ == '__main__':
    year = '2025'
    user_name = '董荣军'
    station = 'Java开发工程师'
    generator_task_excel()
